package com.mano233.server.service.serviceImpl;

import com.mano233.server.po.FastDFSFile;
import com.mano233.server.service.FastDfsService;
import com.mano233.server.tool.FastDfsClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author mano233
 */
@Service
public class FastDfsServiceImpl implements FastDfsService {
    private static Logger logger = LoggerFactory.getLogger(FastDfsServiceImpl.class);

    /**
     * 上传文件到fastDFS
     *
     * @param multipartFile file
     * @return String 返回文件http地址
     * @throws IOException IOEx
     */
    @Override
    public String saveFile(MultipartFile multipartFile) throws IOException {
        String[] fileAbsolutePath = {};
        String fileName = multipartFile.getOriginalFilename();
        if (fileName == null) {
            return null;
        }
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] file_buff = null;
        InputStream inputStream = multipartFile.getInputStream();
        if (inputStream != null) {
            int len1 = inputStream.available();
            file_buff = new byte[len1];
            inputStream.read(file_buff);
            inputStream.close();
        }
        FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
        try {
            fileAbsolutePath = FastDfsClient.upload(file);
        } catch (Exception e) {
            logger.error("upload file Exception!", e);
        }
        if (fileAbsolutePath == null) {
            logger.error("upload file failed,please upload again!");
            return null;
        }
        return FastDfsClient.getTrackerUrl() + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];
    }

    @Override
    public void deleteFile(String groupName, String remoteFileName) {
        try {
            FastDfsClient.deleteFile(groupName, remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

